package com.kuding.sms;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.gson.Gson;
import com.kuding.enums.AliyunSmsApiErrorCode;
import com.kuding.exceptions.VinusException;
import com.kuding.props.AliYunSMSProperty;

public class SmsComponent {

	private Gson gson;

	private AliYunSMSProperty aliYunSMSProperty;

	private final Log logger = LogFactory.getLog(getClass());

	public SmsComponent(Gson gson, AliYunSMSProperty aliYunSMSProperty) {
		this.gson = gson;
		this.aliYunSMSProperty = aliYunSMSProperty;
	}

	public SmsComponent() {
	}

	public void doSendSms(String phone, String smsSignature, String templateCode, Map<String, String> map) {
		IClientProfile profile = DefaultProfile.getProfile(aliYunSMSProperty.getRegionId(),
				aliYunSMSProperty.getAccessKeyId(), aliYunSMSProperty.getSecret());
		try {
			DefaultProfile.addEndpoint(aliYunSMSProperty.getEndPoint(), aliYunSMSProperty.getRegionId(),
					aliYunSMSProperty.getProduct());
			IAcsClient client = new DefaultAcsClient(profile);
			SendSmsRequest request = new SendSmsRequest();
			request.setMethod(MethodType.POST);
			request.setSignName(smsSignature);
			request.setTemplateCode(templateCode);
			request.setTemplateParam(gson.toJson(map));
			request.setPhoneNumbers(phone);
			request.setConnectTimeout((int) aliYunSMSProperty.getConnectionTimeout().toMillis());
			request.setReadTimeout((int) aliYunSMSProperty.getReadTimeout().toMillis());
			if (logger.isDebugEnabled())
				logger.debug(String.format("准备开始发送验证码：%s——%s——%s", phone, templateCode, map.toString()));
			SendSmsResponse httpResponse = client.getAcsResponse(request);
			if (!"OK".equals(httpResponse.getCode())) {
				throw new VinusException("短信验证码出错：" + AliyunSmsApiErrorCode.getMessage(httpResponse.getCode()));
			}
		} catch (ClientException e) {
			throw new VinusException("短信验证码出错：" + e.getMessage());
		}
	}
}
